package com.wqh.user.controller;

import com.wqh.user.entity.User;
import com.wqh.user.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author wanqh
 * @date 2018/01/16 9:46
 * @description:
 */
@RestController
public class UserFeignController {

    private final Logger logger = LoggerFactory.getLogger(UserFeignController.class);
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/feign/user/list")
    public List<User> findAllUser(){
        return  userRepository.findAll();
    }

    /**
     * 根据id查询用户，将参数包含在Request参数
     */
    @GetMapping("/feign/userById")
    public User finUserById(@RequestParam Long id){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info(">>>>>>>>>>>id:{}<<<<<<<<<<<<<",id);
        return userRepository.findOne(id);
    }

    /**
     * 带有Header信息的请求,需要注意的是，使用请求头传递参数，如果参数是中文会出现乱码
     * 所以需要使用 URLEncoder.encode(name,"UTF-8") 先编码
     *       后解码  URLDecoder.decode(name,"UTF-8");
     */
    @GetMapping("/feign/header/user")
    public User findUserHeader(@RequestHeader String name,@RequestHeader Long id,@RequestHeader Integer age) throws UnsupportedEncodingException {
        User user = new User();
        user.setId(id);
        user.setUsername( URLDecoder.decode(name,"UTF-8"));
        user.setAge(age);
        logger.info(">>>>>>>>>>>findUserHeader{}<<<<<<<<<<<<<",user);
        return user;
    }
    /***
     * 带有RequestBody以及请求相应体是一个对象的请求
     */
    @PostMapping("/feign/insert")
    public User insertUser(@RequestBody User user){
        userRepository.save(user);
        return userRepository.findOne(user.getId());
    }
}
